package com.zziq.cloudpicturebank.manager.upload.templateImpl;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.*;
import com.zziq.cloudpicturebank.exception.BusinessException;
import com.zziq.cloudpicturebank.exception.ErrorCode;
import com.zziq.cloudpicturebank.exception.ThrowUtils;
import com.zziq.cloudpicturebank.manager.upload.template.PictureUploadTemplate;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName UrlPictureUpload
 * @Description
 * @Created by ZZIQ
 **/
@Service
public class UrlPictureUpload extends PictureUploadTemplate {

    // 读取配置文件
    @Value("${aliYunAi.apiKey}")
    private String apiKey;
    /**
     * 处理文件
     * @param inputSourse
     * @param file
     * @throws IOException
     */
    @Override
    protected void processFile(Object inputSourse, File file) throws IOException {
        //下载临时文件
        HttpUtil.downloadFile((String)inputSourse, file);
    }

    /**
     * 获取文件原始名称
     * @param inputSourse
     * @return
     */
    @Override
    protected String getOriginalFilename(Object inputSourse) {
        String fileUrl = (String)inputSourse;
        return FileUtil.mainName(fileUrl);
    }

    /**
     * 校验文件的合法性
     * @param inputSourse
     */
    @Override
    protected String validPicture(Object inputSourse) {
        String fileUrl = (String)inputSourse;
        ThrowUtils.throwIf(StrUtil.isBlank(fileUrl),
                ErrorCode.PARAMS_ERROR, "文件地址不能为空");

        try {
            // 1. 验证 URL 格式
            new URL(fileUrl); // 验证是否是合法的 URL
        } catch (MalformedURLException e) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件地址格式不正确");
        }

        // 2. 校验 URL 协议
        ThrowUtils.throwIf(!(fileUrl.startsWith("http://") || fileUrl.startsWith("https://")),
                ErrorCode.PARAMS_ERROR, "仅支持 HTTP 或 HTTPS 协议的文件地址");

        // 3. 发送 HEAD 请求以验证文件是否存在
        HttpResponse response = null;
        //获取文件类型（eg：image/jpg）
        String contentType;
        try {
            Map<String, String> headerMap = new HashMap<>();
            headerMap.put(Header.AUTHORIZATION.getValue(), "Bearer " + apiKey);
            headerMap.put(Header.USER_AGENT.getValue(), "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/133.0.0.0 Safari/537.36 Edg/133.0.0.0 ");

            //发送请求
            response = HttpUtil.createRequest(Method.HEAD, fileUrl).execute();

            // 未正常返回，无需执行其他判断
            if (response.getStatus() != HttpStatus.HTTP_OK) {
                //将请求改为GET请求，兼容不能非HEAD方法
                response = HttpUtil.createRequest(Method.GET, fileUrl).execute();
                 if (response.getStatus() != HttpStatus.HTTP_OK){
                    return "解析图片出错：文件不存在";
                 }
            }

            // 4. 校验文件类型
            contentType = response.header("Content-Type");

            if (StrUtil.isNotBlank(contentType)) {
                // 允许的图片类型
                final List<String> ALLOW_CONTENT_TYPES = Arrays.asList("image/jpeg", "image/jpg", "image/png", "image/webp");
                ThrowUtils.throwIf(!ALLOW_CONTENT_TYPES.contains(contentType.toLowerCase()),
                        ErrorCode.PARAMS_ERROR, "文件类型错误,仅支持 JPEG, JPG, PNG, WEBP 格式");
            }

            // 5. 校验文件大小
            String contentLengthStr = response.header("Content-Length");
            if (StrUtil.isNotBlank(contentLengthStr)) {
                try {
                    long contentLength = Long.parseLong(contentLengthStr);
                    final long TWO_MB = 4 * 1024 * 1024L; // 限制文件大小为 4MB
                    ThrowUtils.throwIf(contentLength > TWO_MB, ErrorCode.PARAMS_ERROR, "文件大小不能超过 4M");
                    //返回文件后缀
                    return contentType.substring(contentType.indexOf('/') + 1);
                } catch (NumberFormatException e) {
                    throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件大小格式错误");
                }
            }
        } finally {
            if (response != null) {
                response.close();
            }

        }
        return "";
    }
}
